from django.db import models
from django.contrib.auth.models import User


class Approval(models.Model):
    """审批流程"""
    APPROVAL_TYPE_CHOICES = [
        ('leave', '请假'),
        ('expense', '报销'),
        ('other', '其他'),
    ]
    
    STATUS_CHOICES = [
        ('pending', '待审批'),
        ('approved', '已通过'),
        ('rejected', '已驳回'),
    ]
    
    applicant = models.ForeignKey(User, on_delete=models.CASCADE, related_name='applications', verbose_name='申请人', db_comment='申请人ID')
    approval_type = models.CharField(max_length=20, choices=APPROVAL_TYPE_CHOICES, verbose_name='类型', db_comment='类型:leave请假,expense报销,other其他')
    title = models.CharField(max_length=200, verbose_name='标题', db_comment='标题')
    content = models.TextField(verbose_name='申请内容', db_comment='申请内容')
    attachments = models.TextField(null=True, blank=True, verbose_name='附件JSON', db_comment='附件JSON')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='pending', verbose_name='状态', db_comment='状态:pending待审批,approved已通过,rejected已驳回')
    current_level = models.IntegerField(default=1, verbose_name='当前审批级别', db_comment='当前审批级别')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间', db_comment='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间', db_comment='更新时间')

    class Meta:
        verbose_name = '审批流程'
        verbose_name_plural = '审批流程'
        db_table = 'zhahuo_approval'
        db_table_comment = '审批流程表'
        ordering = ['-created_at']

    def __str__(self):
        return self.title


class ApprovalRecord(models.Model):
    """审批记录"""
    ACTION_CHOICES = [
        ('approved', '通过'),
        ('rejected', '驳回'),
    ]
    
    approval = models.ForeignKey(Approval, on_delete=models.CASCADE, related_name='records', verbose_name='审批', db_comment='审批ID')
    approver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='approval_records', verbose_name='审批人', db_comment='审批人ID')
    level = models.IntegerField(verbose_name='审批级别', db_comment='审批级别')
    action = models.CharField(max_length=20, choices=ACTION_CHOICES, verbose_name='操作', db_comment='操作:approved通过,rejected驳回')
    comment = models.TextField(null=True, blank=True, verbose_name='审批意见', db_comment='审批意见')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='审批时间', db_comment='审批时间')

    class Meta:
        verbose_name = '审批记录'
        verbose_name_plural = '审批记录'
        db_table = 'zhahuo_approval_record'
        db_table_comment = '审批记录表'
        ordering = ['level', 'created_at']

    def __str__(self):
        return f'{self.approver.username} - {self.action}'
